<?php

class HouseholdController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow admin user 
				'actions'=>array('create','update','view','delete','index','admin','formaddrow','formdeleterow','adminupdate'),
				'roles'=>array('admin'),
			),
			array('allow', // allow admin user 
				'actions'=>array('admin','create','update','delete','adminupdate'),
				'roles'=>array('dataentrysupervisor'),
			),
			array('allow', // allow for authenticated users
				'actions'=>array('admin','create','update', 'adminupdate'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model = new Household();
			
		// $transaction = Yii::app()->db->beginTransaction();
		try
		{
			$model->formAddedByUser = Yii::app()->user->id;
			$model->formLastUpdatedByUser = Yii::app()->user->id;
			$model->createDate = date('d-m-Y');
			$model->lastUpdateDate = date('d-m-Y');
			if($model->save(false) == FALSE)
			{
				Yii::log('failed to save Household: '.var_export($model->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
				throw new CException('Fail to save form');
			}
				
			// $transaction->commit();
			$this->redirect(array('update','id'=>$model->uid));

		}
		catch (Exception $ex) 
		{
			// $transaction->rollback();
			$errorCount = count($model->getErrors());
			$model->addError($errorCount,$ex->getMessage());
			//print_r($ex);exit;
		}
		
		$this->render('update',array(
			'model'=>$model
		));
		
	}
	
	/**
	 * creates a new model row for tabular form.
	 * will show load POST tabular with new row.
	 */
	public function actionFormAddRow()
	{
		if(Yii::app()->request->isAjaxRequest) {
			$items = Yii::app()->request->getPost('Household');
			
			$modelHousehold = array();
			
			if (is_array($items)) { 
				//creating existing model instances + setting attributes
				foreach ($items as $i => $item) {
					$modelHousehold[$i] = new Household();
					$modelHousehold[$i]->setAttributes($item);
				}
			}
            // creating an additional empty model instance
            $modelHousehold[] = new Household();
            
            echo $this->renderPartial('application.views.household/_tabularform_additional', array("modelHousehold" => $modelHousehold));
            exit;

        } else {
            throw new CHttpException(404, 'Unable to resolve the request');
        }
	}
	
	/**
	 * delete model row for tabular form.
	 * will show load POST tabular with delete row.
	 */
	public function actionFormDeleteRow()
	{
		if(Yii::app()->request->isAjaxRequest) {
			$items = Yii::app()->request->getPost('Household');
			$rowIndex = Yii::app()->request->getPost('rowIndex');
			unset($items[$rowIndex]);
			$modelHousehold = array();
			
			if (is_array($items)) { 
				//creating existing model instances + setting attributes
				$i = 0;
				foreach ($items as $item) {
					$modelHousehold[$i] = new Household();
					$modelHousehold[$i]->setAttributes($item);
					$i++;
				}
			}
            
            echo $this->renderPartial('application.views.household/_tabularform_additional', array("modelHousehold" => $modelHousehold));
            exit;

        } else {
            throw new CHttpException(404, 'Unable to resolve the request');
        }
	}
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$this->layout='//layouts/column2household';
		// var_dump($_POST); exit;
		
		$model = $this->loadModel($id);

		$modelFamilyMembers = array();
		$modelFamilyMemberLivingAways = array();
		$modelFamilyMemberMaternalHealths = array();
		$modelFamilyMemberSeniorss = array();
		$modelFamilyMemberEntrepreneurs = array();

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		// validate model objects
		if(isset($_POST['Household']))
		{
			//var_dump($_POST['Household']);exit;
			$isValidHousehold = true;
			$model->setAttributes($_POST['Household']);
			
			// set user last updated by
			$model->formLastUpdatedByUser = Yii::app()->user->id;
			$model->lastUpdateDate = date('d-m-Y');
			
			if(!$model->validate())
			{
				$isValidHousehold = false;
			}
			
			// load POST tabular FamilyMember
			$isValidFamilyMember = true;
			if(isset($_POST['FamilyMember']))
			{
				//print_r($_POST['FamilyMember']); exit;
				$items = $_POST['FamilyMember'];
				foreach ($items as $i => $item) 
				{
					if(!empty($item['uid']))
					{
						$objFamilyMember = FamilyMember::model()->findByPk($item['uid']);
						if($objFamilyMember!==null)
							$modelFamilyMembers[$i] = $objFamilyMember; 
					}
					else
					{
						$modelFamilyMembers[$i] = new FamilyMember();
					}
					
					$modelFamilyMembers[$i]->setAttributes($item);
					if($isValidFamilyMember && !$modelFamilyMembers[$i]->validate())
					{
						$isValidFamilyMember = false;
						$errorCount = count($model->getErrors());
						$model->addError($errorCount, 'Invalid "Family Member" data.');
					}
				}
			}
			
			// load POST tabular FamilyMemberLivingAway
			$isValidFamilyMemberLivingAway = true;
			if(isset($_POST['FamilyMemberLivingAway']))
			{
				$items = Yii::app()->request->getPost('FamilyMemberLivingAway');
				foreach ($items as $i => $item) 
				{
					if(!empty($item['uid']))
					{
						$objFamilyMemberLivingAway = FamilyMemberLivingAway::model()->findByPk($item['uid']);
						if($objFamilyMemberLivingAway != NULL)
							$modelFamilyMemberLivingAways[$i] = $objFamilyMemberLivingAway; 
					}
					else
					{
						$modelFamilyMemberLivingAways[$i] = new FamilyMemberLivingAway();
					}
					
					$modelFamilyMemberLivingAways[$i]->setAttributes($item);
					if($isValidFamilyMemberLivingAway && !$modelFamilyMemberLivingAways[$i]->validate())
					{
						$isValidFamilyMemberLivingAway = false;
						$errorCount = count($model->getErrors());
						$model->addError($errorCount, 'Invalid "Family Member Living Away" data.');
					}
				}
			}
			
			// load POST tabular FamilyMemberMaternalHealth
			$isValidFamilyMemberMaternalHealth = true;
			if(isset($_POST['FamilyMemberMaternalHealth']))
			{
				$items = Yii::app()->request->getPost('FamilyMemberMaternalHealth');
				// var_dump($items);
				foreach ($items as $i => $item) 
				{
					if(!empty($item['uid']))
					{
						$objFamilyMemberMaternalHealth = FamilyMemberMaternalHealth::model()->findByPk($item['uid']);
						if($objFamilyMemberMaternalHealth!==null)
							$modelFamilyMemberMaternalHealths[$i] = $objFamilyMemberMaternalHealth; 
					}
					else
					{
						$modelFamilyMemberMaternalHealths[$i] = new FamilyMemberMaternalHealth();
					}
					$modelFamilyMemberMaternalHealths[$i]->setAttributes($item);
					if($isValidFamilyMemberMaternalHealth && !$modelFamilyMemberMaternalHealths[$i]->validate())
					{
						$isValidFamilyMemberMaternalHealth = false;
						$errorCount = count($model->getErrors());
						$model->addError($errorCount, 'Invalid "Family Member Maternal Health" data.');
					}
				}
			}
			
			// load POST tabular FamilyMemberSeniors
			$isValidFamilyMemberSeniors = true;
			if(isset($_POST['FamilyMemberSeniors']))
			{
				$items = $_POST['FamilyMemberSeniors'];
				foreach ($items as $i => $item) 
				{
					if(!empty($item['uid']))
					{
						$objFamilyMemberSeniors = FamilyMemberSeniors::model()->findByPk($item['uid']);
						if($objFamilyMemberSeniors!==null)
							$modelFamilyMemberSeniorss[$i] = $objFamilyMemberSeniors; 
					}
					else
					{
						$modelFamilyMemberSeniorss[$i] = new FamilyMemberSeniors();
					}
					$modelFamilyMemberSeniorss[$i]->setAttributes($item);
					if($isValidFamilyMemberSeniors && !$modelFamilyMemberSeniorss[$i]->validate())
					{
						$isValidFamilyMemberSeniors = false;
						$errorCount = count($model->getErrors());
						$model->addError($errorCount, 'Invalid "Family Member" data.');
					}
				}
			}

			// load POST tabular FamilyMemberEntrepreneur
			$isValidFamilyMemberEntrepreneur = true;
			if(isset($_POST['FamilyMemberEntrepreneur']))
			{
				$items = $_POST['FamilyMemberEntrepreneur'];
				foreach ($items as $i => $item) 
				{
					if(!empty($item['uid']))
					{
						$objFamilyMemberEntrepreneur = FamilyMemberEntrepreneur::model()->findByPk($item['uid']);
						if($objFamilyMemberEntrepreneur!==null)
							$modelFamilyMemberEntrepreneurs[$i] = $objFamilyMemberEntrepreneur; 
					}
					else
					{
						$modelFamilyMemberEntrepreneurs[$i] = new FamilyMemberEntrepreneur();
					}
					$modelFamilyMemberEntrepreneurs[$i]->setAttributes($item);
					if($isValidFamilyMemberEntrepreneur && !$modelFamilyMemberEntrepreneurs[$i]->validate())
					{
						$isValidFamilyMemberEntrepreneur = false;
						$errorCount = count($model->getErrors());
						$model->addError($errorCount, 'Invalid "Family Member" data.');
					}
				}
			}

			// finaly save 
			// $transaction = Yii::app()->db->beginTransaction();
			try
			{
				if(empty($model->formNum))
					$model->formNum = null;
				else
				{
					
					$results =  Yii::app()->db->createCommand("SELECT COUNT(1) as rowCount FROM household WHERE formNum='".$model->formNum."' AND uid !=".$model->uid)->queryAll();
					if((int)$results[0]["rowCount"] > 0)
					{
						$errorCount = count($model->getErrors());
						$model->addError('formNum', 'Form number '.$model->formNum.' already exists.');
						$model->formNum = null;
					}
				}	
				if($model->save(false) == FALSE)
				{
					Yii::log('failed to save Household: '.var_export($model->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
					throw new CException('Fail to save Household');
				}
				
				// save family member items
				$modelFamilyMemberUids = array();
				foreach($modelFamilyMembers as $item) 
				{
					$item->householdUid = $model->uid;
					if(!empty($item->uid))
					{
						if(!$item->update(false))
						{
							Yii::log('failed to save FamilyMember: '.var_export($item->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
							throw new CException('Fail to save Family Member');
						}
					}	
					else
					{
						if(!$item->save(false))
						{
							Yii::log('failed to save FamilyMember: '.var_export($item->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
							throw new CException('Fail to save Family Member');
						}
					}
					
					$modelFamilyMemberUids[] = $item->uid;
					$item->validate();
				}
				
				// save FamilyMemberLivingAway items
				$modelFamilyMemberLivingAwayUids = array();
				foreach($modelFamilyMemberLivingAways as $item) 
				{
					$item->householdUid = $model->uid;
					
					
					if(!$item->save(false))
					{
						Yii::log('failed to save FamilyMemberLivingAway: '.var_export($item->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
						throw new CException('Fail to save Family Member Living Away');
					}
					
					$modelFamilyMemberLivingAwayUids[] = $item->uid;
					
					$item->validate();
				}
				// save FamilyMemberMaternalHealth items
				$modelFamilyMemberMaternalHealthUids = array();
				foreach($modelFamilyMemberMaternalHealths as $item) 
				{
					$item->householdUid  = $model->uid;
					
					if(!$item->save(false))
					{
						Yii::log('failed to save FamilyMemberMaternalHealth: '.var_export($item->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
						throw new CException('Fail to save Family Member Maternal Health');
					}
					
					$modelFamilyMemberMaternalHealthUids[] = $item->uid;
					$item->validate();
				}
				
				// var_dump($modelFamilyMemberMaternalHealths); exit;
				
				// save FamilyMemberSeniors items
				$modelFamilyMemberSeniorssUids = array();
				foreach($modelFamilyMemberSeniorss as $item) 
				{
					$item->householdUid  = $model->uid;
					
					
					if(!$item->save(false))
					{
						Yii::log('failed to save FamilyMemberSeniors: '.var_export($item->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
						throw new CException('Fail to save Family Member Maternal Health');
					}
					
					$modelFamilyMemberSeniorssUids[] = $item->uid;
					$item->validate();
				}
				
				// save FamilyMemberEntrepreneur items
				$modelFamilyMemberEntrepreneurUids = array();
				foreach($modelFamilyMemberEntrepreneurs as $item) 
				{
					$item->householdUid  = $model->uid;
					
					
					if(!$item->save(false))
					{
						Yii::log('failed to save FamilyMemberEntrepreneur: '.var_export($item->getErrors(), true), CLogger::LEVEL_ERROR, __METHOD__);
						throw new CException('Fail to save Family Member Maternal Health');
					}
					
					$modelFamilyMemberEntrepreneurUids[] = $item->uid;
					$item->validate();
				}
				

				// remove user deleted FamilyMemberLivingAway
				Yii::app()->db->createCommand("delete from familymemberlivingaway where householdUid=".$model->uid . (count($modelFamilyMemberLivingAwayUids) == 0 ? '' : " and uid NOT IN (".implode(',', $modelFamilyMemberLivingAwayUids).")" ))->query();
				
				// remove user deleted FamilyMemberMaternalHealth
				Yii::app()->db->createCommand("delete from familymembermaternalhealth where householdUid=".$model->uid. (count($modelFamilyMemberMaternalHealthUids) == 0 ? '' :  " and uid NOT IN (".implode(',', $modelFamilyMemberMaternalHealthUids).")"))->query();
				
				// remove user deleted Family Members Seniors
				Yii::app()->db->createCommand("delete from familymemberseniors where householdUid=".$model->uid .(count($modelFamilyMemberSeniorssUids) == 0 ? '' : " and uid NOT IN (".implode(',', $modelFamilyMemberSeniorssUids).")"))->query();
				
				// remove user deleted FamilyMemberEntrepreneur
				Yii::app()->db->createCommand("delete from familymemberentrepreneur where householdUid=".$model->uid . (count($modelFamilyMemberEntrepreneurUids) == 0 ? '' : " and uid NOT IN (".implode(',', $modelFamilyMemberEntrepreneurUids).")" ))->query();
				
				// remove user deleted FamilyMember
				Yii::app()->db->createCommand("update familymembermaternalhealth set familyMemberMotherUid = NULL where householdUid=".$model->uid . (count($modelFamilyMemberUids) == 0 ? '' : " and familyMemberMotherUid NOT IN (".implode(',', $modelFamilyMemberUids).")"))->query();
				Yii::app()->db->createCommand("update familymembermaternalhealth set familyMemberChildUid = NULL where householdUid=".$model->uid . (count($modelFamilyMemberUids) == 0 ? '' : " and familyMemberChildUid NOT IN (".implode(',', $modelFamilyMemberUids).")"))->query();
				Yii::app()->db->createCommand("update familymemberlivingaway set familyMemberUid = NULL where householdUid=".$model->uid . (count($modelFamilyMemberUids) == 0 ? '' : " and familyMemberUid NOT IN (".implode(',', $modelFamilyMemberUids).")"))->query();
				Yii::app()->db->createCommand("delete from familymember where householdUid=".$model->uid . (count($modelFamilyMemberUids) == 0 ? '' : " and uid NOT IN (".implode(',', $modelFamilyMemberUids).")"))->query();
				// echo ("delete from familymember where householdUid=".$model->uid . (count($modelFamilyMemberUids) == 0 ? '' : " and uid NOT IN (".implode(',', $modelFamilyMemberUids).")")); exit;
				
				
				// $transaction->commit();
				
				if($isValidHousehold && $isValidFamilyMember && $isValidFamilyMemberLivingAway && $isValidFamilyMemberMaternalHealth) 
				{
				}
			}
			catch (Exception $ex) 
			{
				// $transaction->rollback();
				$errorCount = count($model->getErrors());
				$model->addError($errorCount,$ex->getMessage());
				//print_r($ex);exit;
			}			
		}
		else
		{
			$modelFamilyMembers = FamilyMember::model()->findAll(array(
				'condition'=>'householdUid=:householdUid',
				'params'=>array(':householdUid'=>$id)
			));
			
			 
			$modelFamilyMemberLivingAways = FamilyMemberLivingAway::model()->findAll(array(
				'condition'=>'householdUid=:householdUid',
				'params'=>array(':householdUid'=>$id)
			));
			
			$modelFamilyMemberMaternalHealths = FamilyMemberMaternalHealth::model()->findAll(array(
				'condition'=>'householdUid=:householdUid',
				'params'=>array(':householdUid'=>$id)
			));
			
			$modelFamilyMemberSeniorss = FamilyMemberSeniors::model()->findAll(array(
				'condition'=>'householdUid=:householdUid',
				'params'=>array(':householdUid'=>$id)
			));
			
			$modelFamilyMemberEntrepreneurs = FamilyMemberEntrepreneur::model()->findAll(array(
				'condition'=>'householdUid=:householdUid',
				'params'=>array(':householdUid'=>$id)
			));
		}
		
		// var_dump($modelFamilyMemberSeniorss); exit;
		$this->render('update',array(
			'model'=>$model,
			'modelFamilyMember'=> $modelFamilyMembers,
			'modelFamilyMemberLivingAway'=> $modelFamilyMemberLivingAways,
			'modelFamilyMemberMaternalHealth'=> $modelFamilyMemberMaternalHealths,
			'modelFamilyMemberSeniors'=> $modelFamilyMemberSeniorss,
			'modelFamilyMemberEntrepreneur'=> $modelFamilyMemberEntrepreneurs,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'admin' page.
	 */
	public function actionAdminUpdate()
	{
				
		// validate model objects
		if(isset($_POST['uid']) && !empty($_POST['formPostStatus']))
		{
			
			try
			{		
				//echo "UPDATE household SET formPostStatus='".$_POST['formPostStatus']."' WHERE uid IN (".implode(',', $_POST['uid']).")"; exit;		
				Yii::app()->db->createCommand("UPDATE household SET formPostStatus='".$_POST['formPostStatus']."' WHERE uid IN (".implode(',', $_POST['uid']).")")->query();
					
			}
			catch (Exception $ex) 
			{
				// $errorCount = count($model->getErrors());
				// $model->addError($errorCount,$ex->getMessage());
				print_r($ex);exit;
			}			
		}
		
		$this->redirect(array('admin'));
		
	}

	
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// delete FamilyMemberLivingAway
			Yii::app()->db->createCommand("delete from familymemberlivingaway where householdUid=$id")->query();
				
			// delete FamilyMemberMaternalHealth
			Yii::app()->db->createCommand("delete from familymembermaternalhealth where householdUid=$id")->query();
				
			// delete Family Members Seniors
			Yii::app()->db->createCommand("delete from familymemberseniors where householdUid=$id")->query();
				
			// delete FamilyMemberEntrepreneur
			Yii::app()->db->createCommand("delete from familymemberentrepreneur where householdUid=$id")->query();
				
			// delete FamilyMember
			Yii::app()->db->createCommand("delete from familymember where householdUid=$id")->query();
			
			// delete Household
			Yii::app()->db->createCommand("delete from household where uid=".$id)->query();
			
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Household');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model = new Household('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Household']))
			$model->attributes=$_GET['Household'];
		
		// list form added by operator themself 
		if(Yii::app()->user->userRoleId == 7)
		{
			$model->formAddedByUser = Yii::app()->user->id;
		}
		
		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Household::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='household-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
